<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;

class Message
{
    use Jump;

    // 查看
    public function detail(int $id)
    {
        $vo = db('message')->where('id', $id)->find();
        if (!$vo) {
            $this->error('留言不存在');
        }
        return view()->with('vo', $vo);
    }

    // 添加
    public function add(array $req)
    {
        if ($this->isPost()) {
            $r = model('common.message')->save($req);
            $audit = site('msg_audit', 0);
            $msg = $audit == 0 ? '留言成功' : '留言添加成功，请耐心等待审核...';
            $this->_jump([$msg, '留言失败'], $r, 'index/index');
        }
        $this->error('非法操作');
    }

    // 点赞
    public function poll(int $id)
    {
        if ($this->isAjax()) {
            $ip = get_int_ip();
            $poll = db('message_poll');
            $isPoll = $poll->where('message_id', $id)->where('poll_ip', $ip)->find();
            if (!$isPoll) {
                $data = [];
                $data['message_id'] = $id;
                $data['poll_ip'] = $ip;
                $data['create_time'] = time();
                $data['status'] = 1;
                $poll->insert($data);
                db('message')->where('id', $id)->setInc('poll_count');
                $this->success('点赞成功');
            }
            $this->error('您已点赞');
        }
        $this->error('非法操作');
    }

    // 权限验证
    protected function checkAuth(int $level = 1)
    {
        if (session('user.level') < $level) {
            $this->error('权限不足');
        }
    }

    // 回复留言
    public function reply(array $req)
    {
        $this->checkAuth(3);
        if ($this->isPost()) {
            $r = model('common.message')->reply($req);
            $this->_jump(['回复成功', '回复失败'], $r, 'index/index');
        }
        $this->error('非法操作');
    }

    // 置顶操作
    public function top(int $id)
    {
        $this->checkAuth(3);
        if ($this->isAjax()) {
            $message = db('message');
            $act = '置顶';
            $r = $message->where('id', $id)->where('is_top', 0)->setField('is_top', 1);
            if (!$r) {
                $act = '取消置顶';
                $r = $message->where('id', $id)->where('is_top', 1)->setField('is_top', 0);
            }
            $this->_jump([$act . '成功', $act . '失败'], $r, 'index/index');
        }
        $this->error('非法操作');
    }

    // 通过审核或设为待审
    public function audit(int $id)
    {
        $this->checkAuth(3);
        if ($this->isAjax()) {
            $message = db('message');
            $act = '审核';
            $r = $message->where('id', $id)->where('status', 0)->setField('status', 1);
            if (!$r) {
                $act = '设为待审';
                $r = $message->where('id', $id)->where('status', 1)->setField('status', 0);
            }
            $this->_jump([$act . '成功', $act . '失败'], $r, 'index/index');
        }
        $this->error('非法操作');
    }
}